package 牛客_面试必刷.Month07.day08;

public class 链表中环的入口 {
    public ListNode EntryNodeOfLoop(ListNode pHead) {
        //快慢指针相遇节点的距离到环的距离和头结点到环的距离相等
        //首先找到相遇节点
        ListNode meetNode = same(pHead);
        if(meetNode == null) return null;
        while(pHead != meetNode){
            pHead = pHead.next;
            meetNode = meetNode.next;
        }
        return pHead;
    }

    //寻找相遇的节点
    public ListNode same(ListNode head){
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow) return slow;
        }
        return null;
    }
}
